#include <chipKITEthernet.h>
#include <SPI.h>

/*
  This sketch is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This sketch is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this sketch; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
/************************************************************************/
/*  Revision History:							*/
/* 									*/
/* 8/08/2011 Digilent Inc. (KeithV)					*/
/* Updated for use with the chipKIT Max32 and chipKIT Network Shield	*/
/*									*/
/************************************************************************/

/*
  Web  Server
 
 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield. 
 
 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)
 
 created 18 Dec 2009
 by David A. Mellis
 modified 4 Sep 2010
 by Tom Igoe
 
 */

// Enter a MAC address and IP address for your controller below. 
// A zero MAC address means that the chipKIT MAC is to be used
byte mac[] = { 0x00, 0x04, 0xa3, 0x52, 0x90, 0x5b };
byte ip[] = { 192,168,1,2 };

char cmd[15];    // Nothing magical about 15, increase these if you need longer commands/parameters
char param1[15];
char param2[15];

char ANALOG_INPUT_URL[] = "?submit_analog=Show+analog+input%21";
char LED_ON_URL[] = "?LED_ON=Turn+on+LED";
char LED_OFF_URL[] = "?LED_OFF=Turn+off+LED";

String LED2ONchecked = "";
String LED2OFFchecked = "";

#define bufferMax 128
int bufferSize;
char buffer[bufferMax];


// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
Server server(80);

void setup()
{
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(78,OUTPUT);
  pinMode(79,OUTPUT);
  pinMode(80,OUTPUT);
  pinMode(81,OUTPUT);
  digitalWrite(8, LOW); // set the LED off
  digitalWrite(9, HIGH);
  digitalWrite(10, LOW);
  digitalWrite(11, HIGH);
  digitalWrite(78, LOW);
  digitalWrite(79, LOW);
  digitalWrite(80, LOW);
  digitalWrite(81, LOW);
  
  Serial.begin(9600);
  Serial1.begin(115200);
  //Ethernet.begin(mac, ip);
  Ethernet.begin();  // this will use DHCP
  server.begin();
  Serial.println("Starting server...");
  //LED2check="checked='checked'";
  //Serial.println(LED2check);
}

void loop()
{
  // listen for incoming clients
  Client client = server.available();
  if (client) {
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    //client.print(hej);
    bufferSize = 0;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply

        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
             
          Serial.println("Calling ParseReceivedRequest()...");
          ParseReceivedRequest();
          
          //HTML-webpage: 
          client.print("<html>");
          client.print("<head>"
                         "<title>Arduino Remote Control</title>"
                         "<meta name='author' content='Grupp2'/>" 
                         "<meta name='description' content='arduino webserver'/>"
                         "<meta http-equiv='content-type' content='text/html; charset=UTF-8/>"
                         "</head");
                         
          client.print("<body>");
          client.print("<div title='page'>"
                           "<div title='header'>"
                             "<h1 align='center'>Arduino Remote control</h1>"//send first heading
                             "<hr />"
                             "<br />"
                           "</div><!--/header-->"
                           "<div title='content'>"
                             "<form method='get' name='homepage'>"
                               "<fieldset>"
                                 "<legend>Analog Input</legend>" 
                                 "<input type='submit' name='submit_analog' value='Show analog input!'><br/>"
                               "</fieldset>"
                               "<fieldset>"
                                 "<legend>Lamps</legend>"
                                 "<div title='Lamp1'>"
                                   "<p>"
                                   "<b>Lamp 1&nbsp;&nbsp;&nbsp;</b>"
                                   "<label for='L1_ON'>ON:</label>"
                                   "<input type='radio' name='L1' id='L1_ON' value='ON' onclick='this.form.submit();'/>"
                                   "<label for='L1_OFF'>OFF:</label>"
                                   "<input type='radio' name='L1' id='L1_OFF' value='OFF' onclick='this.form.submit();'/>"
                                   "</p>"
                                 "</div><!--/Lamp1-->"
                                 "<div title='Lamp2'>"
                                   "<p>"
                                   "<b>Lamp 2&nbsp;&nbsp;&nbsp;</b>"
                                   "<label for='L2_ON'>ON:</label>"
                                   "<input type='radio' name='L2' id='L2_ON' value='ON' ");
                      client.print(LED2ONchecked);
                      client.print(" onclick='this.form.submit();'/>"
                                   "<label for='L2_OFF'>OFF:</label>"
                                   "<input type='radio' name='L2' id='L2_OFF' value='OFF' ");
                      client.print(LED2OFFchecked);            
                      client.print("onclick='this.form.submit();'/>"
                                   "</p>"
                                 "</div><!--/Lamp2-->"
                                 "<div title='Lamp3'>"
                                   "<p>"
                                   "<b>Lamp 3&nbsp;&nbsp;&nbsp;</b>"
                                   "<label for='L3_ON'>ON:</label>"
                                   "<input type='radio' name='L3' id='L3_ON' value='ON' onclick='this.form.submit();'/>"
                                   "<label for='L3_OFF'>OFF:</label>"
                                   "<input type='radio' name='L3' id='L3_OFF' value='OFF' onclick='this.form.submit();'/>"
                                   "</p>"
                                 "</div><!--/Lamp3-->"
                                 "<div title='Lamp4'>"
                                   "<p>"
                                   "<b>Lamp 4&nbsp;&nbsp;&nbsp;</b>"
                                   "<label for='L4_ON'>ON:</label>"
                                   "<input type='radio' name='L4' id='L4_ON' value='ON' onclick='this.form.submit();'/>"
                                   "<label for='L4_OFF'>OFF:</label>"
                                   "<input type='radio' name='L4' id='L4_OFF' value='OFF' onclick='this.form.submit();'/>"
                                   "</p>"
                                 "</div><!--/Lamp4-->"
                               "</fieldset>"
                               "<fieldset>"
                                 "<legend>IAR</legend>"
                                 "<div title='LED1'>"
                                   "<p>"
                                   "<b>LED 1&nbsp;&nbsp;&nbsp;</b>"
                                   "<label for='IAR_L1_ON'>ON:</label>"
                                   "<input type='radio' name='IAR_L1' id='IAR_L1_ON' value='ON' onclick='this.form.submit();'/>"
                                   "<label for='IAR_L1_OFF'>OFF:</label>"
                                   "<input type='radio' name='IAR_L1' id='IAR_L1_OFF' value='OFF' onclick='this.form.submit();'/>"
                                   "</p>"
                                 "</div><!--/LED1-->"
                                 "<div title='IAR_DISCO'>"
                                   "<p>"
                                   "<b>Disco &nbsp;&nbsp;&nbsp;</b>"
                                   "<label for='IAR_DISCO_ON'>ON:</label>"
                                   "<input type='radio' name='IAR_DISCO' id='IAR_DISCO_ON' value='ON' onclick='this.form.submit();'/>"
                                   "</p>"
                                 "</div><!--/IAR_DISCO-->"
                               "</fieldset>"
                             "</form>"
                           "</div><!--/content-->"
                         "</div><!--/page-->");
          client.println("</body>");
          client.println("</html>");                        
          //End of HTML-webpage

          if ( strcmp(cmd,ANALOG_INPUT_URL) == 0 ) 
          {
            for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
              client.print("analog input ");
              client.print(analogChannel);
              client.print(" is ");
              client.print(analogRead(analogChannel));
              client.println("<br />");
            }  
          }
          
          else if ( strcmp(cmd,"?L1=ON") == 0 )
          {
           digitalWrite(8,HIGH);
           
           if (digitalRead(8) == HIGH) client.println("LED1 on");
             else (client.println("LED1 error"));
          }
          
         else if ( strcmp(cmd,"?L1=OFF") == 0 )
         {
           digitalWrite(8,LOW);         
           if (digitalRead(8) == LOW) client.println("LED1 off");
             else (client.println("LED1 error"));    
         }
         
         else if ( strcmp(cmd,"?L2=ON") == 0 )
         {
           digitalWrite(9,HIGH);
           LED2OFFchecked = "";
           LED2ONchecked = "checked='checked'";
           Serial.println("LED2OFF: " + LED2OFFchecked);
           Serial.println("LED2ON: " + LED2ONchecked);          
           if (digitalRead(9) == HIGH) client.println("LED2 on");
             else (client.println("LED2 error"));    
         }
         
         else if ( strcmp(cmd,"?L2=OFF") == 0 )
         {
           digitalWrite(9,LOW); 
           LED2ONchecked = "";
           LED2OFFchecked = "checked='checked'";
           Serial.println("LED2OFF: " + LED2OFFchecked);
           Serial.println("LED2ON: " + LED2ONchecked);
           if (digitalRead(9) == LOW) client.println("LED2 off");
             else (client.println("LED2 error"));    
         }
         
         else if ( strcmp(cmd,"?L3=ON") == 0 )
         {
           digitalWrite(10,HIGH);         
           if (digitalRead(10) == HIGH) client.println("LED3 on");
             else (client.println("LED3 error"));    
         }
         
         else if ( strcmp(cmd,"?L3=OFF") == 0 )
         {
           digitalWrite(10,LOW);         
           if (digitalRead(10) == LOW) client.println("LED3 off");
             else (client.println("LED3 error"));    
         }
         
         else if ( strcmp(cmd,"?L4=ON") == 0 )
         {
           digitalWrite(11,HIGH);         
           if (digitalRead(11) == HIGH) client.println("LED4 on");
             else (client.println("LED4 error"));    
         }
         
         else if ( strcmp(cmd,"?L4=OFF") == 0 )
         {
           digitalWrite(11,LOW);         
           if (digitalRead(11) == LOW) client.println("LED4 off");
             else (client.println("LED4 error"));    
         }
         
         else if ( strcmp(cmd,"?IAR_L1=ON") == 0 )
         {
           Serial1.write('b');         
         }
         
         else if ( strcmp(cmd,"?IAR_L1=OFF") == 0 )
         {
           Serial1.write('c');         
         }
         
         else if ( strcmp(cmd,"?IAR_DISCO=ON") == 0 )
         {
           int iard = 1;
           while (iard < 10) {
             Serial1.write('b');
             delay(50);
             Serial1.write('c');
             delay(50);
             Serial1.write('e');
             delay(50);
             Serial1.write('f');
             delay(50);
             Serial1.write('h');
             delay(50);
             Serial1.write('i');
             delay(50);
             Serial1.write('k');
             delay(50);
             Serial1.write('l');
             delay(50);
             iard++;
           }
         }
         
         else if ( strcmp(cmd,"?IAR_DISCO=OFF") == 0 )
         {
           Serial1.write('c');
           Serial1.write('f'); 
           Serial1.write('i');
           Serial1.write('k');        
         }
          break;
        }
        
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }

         else if (bufferSize < bufferMax) {
         currentLineIsBlank = false;
         buffer[bufferSize++] = c; 
        } 
      }
    }
    
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
  }
}

void ParseReceivedRequest()
{
  Serial.println("in ParseReceivedRequest");
  Serial.println(buffer);
  
  //Received buffer contains "GET /cmd/param1/param2 HTTP/1.1".  Break it up.
  char* slash1;
  //char* slash2;
  //char* slash3;
  char* space2;
  
  Serial.println("variables inicilized..");
  Serial.println("Look for first slash");
  slash1 = strstr(buffer, "/") + 1; // Look for first slash
    //Serial.println("Look for second slash");
  //slash2 = strstr(slash1, "/") + 1; // second slash
    //Serial.println("Look for third slash");
  //slash3 = strstr(slash2, "/") + 1; // third slash
  Serial.println("Space after second slash...");
  space2 = strstr(slash1, " ") + 1; // space after second slash (in case there is no third slash)
  //if (slash1 > space2) slash2=slash1;
  
  Serial.println("URL splitted..");
  
  PrintString("slash1",slash1);
  //PrintString("slash2",slash2);
  //PrintString("slash3",slash3);
  PrintString("space2",space2);
  
  
  // strncpy does not automatically add terminating zero, but strncat does! So start with blank string and concatenate.
  cmd[0] = 0;
  //param1[0] = 0;
  //param2[0] = 0;
  strncat(cmd, slash1, space2-slash1-1);
  //strncat(param1, slash2, slash3-slash2-1);
  //strncat(param2, slash3, space2-slash3-1);
  
  PrintString("cmd",cmd);
  //PrintString("param1",param1);
  //PrintString("param2",param2);
  
}

void PrintString(char* label, char* str)
{
  Serial.print(label);
  Serial.print("=");
  Serial.println(str);
}
